package com.yisu.expressway.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by zhouyang on 2016/3/25.
 */
public class PhotoSaveUtil {

    private OnPhotoSaveListener mListener = null;

    public PhotoSaveUtil setListener(OnPhotoSaveListener listener){
        mListener = listener;
        return this;
    }

    public String saveBitmap(Context context, Bitmap bitmap, boolean bToast){

        final File folder = getStoragePath(context);
        final String fileName = File.separator + System.currentTimeMillis() + ".jpg";

        String filePath = saveBitmap(context, folder, fileName, bitmap, bToast);

        return filePath;
    }



    public void save(Context context, String orignalPath, boolean bToast){
        saveInternal(context, orignalPath, null, bToast);
    }

    public void save(Context context, String orignalPath, String destFileName, boolean bToast){
        saveInternal(context, orignalPath, destFileName, bToast);
    }

    //保存来自网络的图片
    private void saveInternal(final Context context, String orignalPath, String destFileName,final boolean bToast){
        final File folder = getStoragePath(context);

        final String fileName;
        if (null == destFileName){
            fileName = File.separator + System.currentTimeMillis() + ".jpg";
        }else{
            fileName = File.separator + destFileName + ".jpg";
        }

        Glide.with(context.getApplicationContext())
                .load(orignalPath)
                .asBitmap()
                .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        saveBitmap(context, folder, fileName, resource, bToast);
                    }
                });

        return;
    }

    private File getStoragePath(Context context){

        //如果选用外部存储，用户查了sd卡，且在设置里选择了sd卡存储，context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)，保存在/storage/emulated/1/Android/data/com.hcnm.huaban/files/Pictures
        //如果用户插sd卡了，但设置里选择了手机内部存储，context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)，保存在/storage/emulated/0/Android/data/com.hcnm.huaban/files/Pictures，该位置实际是/data/data/com.hcnm.huaban/files/Pictures,
        //以上两个位置，如果app被删除，app保存的图片会被一并删除，但mediascaner不会扫描到这些内容，而且内容的删除，需要app自己搞定

        //拟采用以下方案
        //图片保存在/storage/emulated/0/mocon目录，由Environment.getExternalStorageDirectory()获取。
        //1.留白和足记，都是保存在此目录下的
        //2.该目录不随app删除而删除
        //3.该目录下的内容，可以被系统自带的图库（第三方）删除，app无需维护
        //4.该目录下的图片，可以被系统mediascaner自动扫描到。

        String eStorageDir = Environment.getExternalStorageDirectory().toString() + File.separator + "yisu";

        File folder = new File(eStorageDir);
        if (!folder.exists()){
            folder.mkdir();
        }

        return folder;
    }

    private String saveBitmap(Context context, File folder, String fileName, Bitmap bitmap, boolean bToast){
        File file = new File(folder, fileName);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (null != fout) {
                    fout.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        if (bToast){
            scanFile(context, file);
            Toast.makeText(context, "照片已保存，请到相册里查看！", Toast.LENGTH_SHORT).show();
        }

        String localPath = file.getAbsolutePath();
        if (null != mListener){
            mListener.onPhotoSaved(localPath);
        }

        return localPath;
    }

    private void scanFile(Context context, File file) {
        Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        scanIntent.setData(Uri.fromFile(file));
        context.sendBroadcast(scanIntent);
    }

    public interface OnPhotoSaveListener{
        public void onPhotoSaved(String localPath);
    }
}
